import Axios from 'axios';
import router from '../router/router.js';

//request 拦截请求

Axios.interceptors.request.use((config)=>{
    if(window.sessionStorage.getItem('token')){
        config.headers.Authorization = `${window.sessionStorage.getItem('token')}`;
    }
    return config;
},
err => {
    return Promise.reject(err);
})

//response 拦截
let currentErr = 0;
Axios.interceptors.response.use(
  undefined,
  error => {
    let res = error.response;
    switch (res.status) {
      case 401:
        // 返回 401 清除token信息并跳转到登录页面
        window.console.log('未登录 或者token过期');
        currentErr++;
        if (currentErr === 1) {
            router.replace({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}
            })
        }
        break;
      case 403:
        window.console.log('请注册账号');
        currentErr++;
        if (currentErr === 1) {
            window.sessionStorage.clear();
            router.replace({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}
            })
        }
        break;
      case 500:
        window.console.log('服务器错误');
        break;
    }
    return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  });